package com.jnc.core.config.jdbc;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.jnc.common.constant.SysConstant;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author: jjn
 * @Date: 2018/5/31
 * @Desc: Base数据源配置
 */
@Configuration
@EnableTransactionManagement   //开启事务注解(配置方法上的注解@Transactional使用)
public class BaseDataSourceConfig {

    // 指定该数据源对应的mapper接口目录，以便跟其他数据源隔离
    static final String MAPPER_LOCATION = "classpath:mybatis/*/*/*.xml";

    /**
     * 获取数据源datasource
     * @return
     */
    @Bean(name = "baseDataSource")
    @Qualifier("baseDataSource")
    @Primary
    @ConfigurationProperties(prefix = "base.datasource")
    public DataSource baseDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 获取sqlSessionFactory工厂实例
     * @return
     * @throws Exception
     */
    @Bean(name = "baseSqlSessionFactory")
    @Qualifier("baseSqlSessionFactory")
    @Primary
    public SqlSessionFactory baseSqlSessionFactory(@Qualifier("baseDataSource") DataSource baseDataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(baseDataSource);

        //添加xml目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factory.setMapperLocations(resolver.getResources(BaseDataSourceConfig.MAPPER_LOCATION));

        return factory.getObject();
    }

    @Bean(name = "baseSqlSessionTemplate")
    @Qualifier("baseSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate baseSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory baseSqlSessionFactory){
        SqlSessionTemplate baseSqlSessionTemplate = new SqlSessionTemplate(baseSqlSessionFactory);
        return baseSqlSessionTemplate;
    }

    /**
     * 事务管理器
     * @return
     */
    @Bean(name = SysConstant.TX_BASE_NAME)
    @Qualifier(SysConstant.TX_BASE_NAME)
    @Primary
    public DataSourceTransactionManager baseTransactionManager(){
        return new DataSourceTransactionManager(baseDataSource());
    }




}
